﻿/**
 *    Copyright 2012 Yohan Courbe
 *
 *  Licensed under the Apache License, Version 2.0 (the "License 
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *      
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

using System;
using System.Net;
using PacketDotNet;

namespace NetworkAnalyzer.Engines.UdpTransfertTracker
{
    internal class UdpTransfert
    {
        #region private fields

        public IPAddress Localhost { get; private set; }

        public ushort Localport { get; private set; }

        public IPAddress Remotehost { get; private set; }

        public DateTime StartTime { get; private set; }

        public ushort Remoteport { get; private set; }

        public DateTime EndTime { get; private set; }

        public ApplicativeProtocol ApplicativeProtocol { get; private set; }

        public int DownloadBandwidth { get; private set; }

        public int UploadBandiwdth { get; private set; }

        public bool IsTerminated { get; private set; }

        public int NumberOfPackets { get; private set; }

        public bool HasBeenSavedInDatabase { get; set; }

        #endregion

        #region hidden fields

        private const int MaxTTL = 300;
        private int _timeToLive = MaxTTL;

        #endregion

        #region constructors

        public UdpTransfert(IPAddress localhost, ushort localport, IPAddress remotehost, ushort remoteport)
        {
            ApplicativeProtocol = ApplicativeProtocol.Unknown;
            StartTime = DateTime.Now;
            Localhost = localhost;
            Remotehost = remotehost;
            Localport = localport;
            Remoteport = remoteport;
        }

        #endregion

        #region private methods

        private void TerminateTransfert()
        {
            IsTerminated = true;
            EndTime = DateTime.Now;
            EndTime = EndTime.AddSeconds(-MaxTTL);
        }

        private void ResetTimeToLive()
        {
            _timeToLive = MaxTTL; // Reset timetolive.   
        }

        #endregion

        #region public methods

        public void AddPacket(Packet packet, IpPacket ipPacket, UdpPacket udpPacket)
        {
            ResetTimeToLive();

            NumberOfPackets++;

            var isLocalSource = ipPacket.SourceAddress.IsLocalHost();

            if (isLocalSource)
            {
                UploadBandiwdth += packet.Bytes.Length;
            }
            else
            {
                DownloadBandwidth += packet.Bytes.Length;
            }

            if (ApplicativeProtocol == ApplicativeProtocol.Unknown)
            {
                ApplicativeProtocol = Tools.GetApplicativeProtocol(isLocalSource ? udpPacket.DestinationPort : udpPacket.SourcePort);
            }
        }

        public bool Match(IPAddress localhost, ushort localport, IPAddress remotehost, ushort remoteport)
        {
            if (IsTerminated)
            {
                return false;
            }

            if (!Equals(Localhost, localhost))
            {
                return false;
            }

            if (Localport != localport)
            {
                return false;
            }

            if (!Equals(Remotehost, remotehost))
            {
                return false;
            }

            if (Remoteport != remoteport)
            {
                return false;
            }

            return true;
        }

        public void DecreaseTtl()
        {
            if (_timeToLive <= 0 && !IsTerminated)
            {
                TerminateTransfert();
            }
            else
            {
                _timeToLive--;
            }
        }

        #endregion
    }
}